package gr.handmademarket.bl.operations;

import gr.handmademarket.hibernate.HibernateUtil;
import gr.handmademarket.po.implementations.KeyGenerator;
import gr.handmademarket.po.implementations.ProductCategory;
import gr.handmademarket.po.implementations.Seller;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * operation that saves a seller.
 */
public class RegisterSellerOperation {

	/**
	 * fetching key value of categories.
	 */
	@SuppressWarnings("nls")
	private static final String nextKeyString = 
			"select kg from KeyGenerator kg where kg.tableName = :entityName";
	
	/**
	 * fetching creators categories.
	 */
	@SuppressWarnings("nls")
	private static final String creatorsString = 
			"select c from ProductCategory c where c.code = 2";
	
	/**
	 * the seller.
	 */
	private Seller seller;
	
	/**
	 * Creates a new RegisterSellerOperation object. 
	 *
	 */
	public RegisterSellerOperation() {
		// empty
	}
	
	/**
	 * execution method.
	 */
	@SuppressWarnings("nls")
	public void execute(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery(nextKeyString);
		query.setString("entityName", "categories");
		KeyGenerator keyGen = (KeyGenerator) query.list().get(0);
		Integer nextVal = keyGen.getKeyValue() + 1;
		seller.setCode(nextVal);
		keyGen.setKeyValue(nextVal);
		
		Query creatorsQuery = session.createQuery(creatorsString);
		ProductCategory pc = (ProductCategory) creatorsQuery.list().get(0);
		seller.setParent(pc);
		
        session.save(seller);
        session.getTransaction().commit();
	}

	/**
	 * @return seller.
	 */
	public Seller getSeller() {
		return seller;
	}

	/**
	 * @param seller
	 */
	public void setSeller(Seller seller) {
		this.seller = seller;
	}
	
}
